package com.lenovo.smarttraffic.ui.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.ResultReceiver;
import android.support.design.widget.TextInputLayout;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.internal.GsonBuildConfig;
import com.lenovo.smarttraffic.InitApp;
import com.lenovo.smarttraffic.R;
import com.lenovo.smarttraffic.api.VolleyCallBack;
import com.lenovo.smarttraffic.bean.GsonBean.UserDetailBean;
import com.lenovo.smarttraffic.bean.LitepalBean.DBUserInfoBean;
import com.lenovo.smarttraffic.util.VolleyUtil;

import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.LitePal;
import org.litepal.crud.callback.SaveCallback;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;

/**
 * @author Amoly
 * @date 2019/4/11.
 * description：
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener {

    private EditText mEditTextName;
    private EditText mEditTextPassword;
    private TextInputLayout mTextInputLayoutName;
    private TextInputLayout mTextInputLayoutPswd;
    private CheckBox mCheckbox;
    private SharedPreferences.Editor mEditor;
    private ProgressDialog mProgrssDialog;
    private static final String TAG = "LoginActivity";
    private static final String USER_INFO = "com.lenovo.smarttraffic.ui.activity.LoginActivity.userinfo";
    private static final String USER_NAME = "com.lenovo.smarttraffic.ui.activity.LoginActivity.username";
    private static final String USER_PASSWD = "com.lenovo.smarttraffic.ui.activity.LoginActivity.passwd";

    private static final String USER_ISCHECKED = "com.lenovo.smarttraffic.ui.activity.LoginActivity.ischeck";
    private static final String USER_SERVER_NAME="com.lenovo.smarttraffic.ui.activity.LoginActivity.servername";

    @Override
    protected int getLayout() {
        return R.layout.activity_login;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mEditor = getSharedPreferences(USER_INFO, MODE_PRIVATE).edit();
        mProgrssDialog=new ProgressDialog(this);
        //1.1
        initView();
        checkForRemember();

    }

    private void checkForRemember() {
        if(LoginActivity.IsChecked(this)){
            mCheckbox.setChecked(true);
            mEditTextName.setText(LoginActivity.getUserName(this));
            mEditTextPassword.setText(LoginActivity.getUserPasswd(this));
        }
    }

    private void initView() {
        initToolBar(getString(R.string.login));
        mTextInputLayoutName = findViewById(R.id.textInputLayoutName);
        mTextInputLayoutPswd = findViewById(R.id.textInputLayoutPassword);
        mEditTextName = findViewById(R.id.editTextName);
        mTextInputLayoutName.setErrorEnabled(true);
        mEditTextPassword = findViewById(R.id.editTextPassword);
        mTextInputLayoutPswd.setErrorEnabled(true);
        mCheckbox = findViewById(R.id.jzpwdCB);
        Button loginButton = findViewById(R.id.loginBtn);
        loginButton.setOnClickListener(this);
        mEditTextName.addTextChangedListener(new TextWatcher() {
            @Override/*内容要改变之前调用*/
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                /*从start位置开始，count个字符（空字符是0）将被after个字符替换*/

            }

            @Override/*内容要改变时调用*/
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                /*说明在s字符串中，从start位置开始的count个字符刚刚取代了长度为before的旧文本*/
            }

            @Override/*内容要改变之后调用*/
            public void afterTextChanged(Editable s) {
                //这个方法被调用，那么说明s字符串的某个地方已经被改变。
                checkName(s.toString(), false);
            }
        });
        mEditTextPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                checkPwd(s.toString(), false);
            }
        });
    }

    //网络设置
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.network_setting, menu);
        return true;
    }

    //处理网络设置，1.5
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_settings:
                startActivity(new Intent(LoginActivity.this, NetWorkActivity.class));
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.loginBtn) {
            hideSoftInput(v);//对应着隐藏输入法
            if (!checkName(mEditTextName.getText(), true)){
                return;
            }
            if (!checkPwd(mEditTextPassword.getText(), true))
            {
                return;
            }
//登录，存储
            userLogin();
        }
    }

    private void userLogin() {
        mProgrssDialog.show();
        String userName = mEditTextName.getText().toString();
        String userPasswd = mEditTextPassword.getText().toString();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("UserName", userName);
            jsonObject.put("UserPwd", userPasswd);
        } catch (JSONException e) {
        }
        VolleyUtil.post("user_login.do", jsonObject, new VolleyCallBack() {
            @Override
            public void onSucceess(JSONObject jsonObject, String response) {
                if (jsonObject.optString("RESULT").equals("S")) {
                    Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                    mProgrssDialog.dismiss();
                    mEditor.putBoolean(USER_ISCHECKED,mCheckbox.isChecked());
                    if(mCheckbox.isChecked()){
                        mEditor.putString(USER_NAME,userName)
                                .putString(USER_PASSWD,userPasswd).commit();
                    }
                    finish();
                    //todo
//                        queryName();
                }
            }

            @Override
            public void onFailure(String onError) {
                Log.d(TAG, "onFailure: "+onError);
            }
        });
    }

    /**
     * 查询保存真名
     */
    private void queryName() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("UserName","user1");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        VolleyUtil.post("GetSUserInfo.do", jsonObject, new VolleyCallBack() {
            @Override
            public void onSucceess(JSONObject jsonObject, String response) {
                UserDetailBean userDetailBean = new Gson().fromJson(response, UserDetailBean.class);
                if(userDetailBean.getRESULT().equals("S")){
                    List<UserDetailBean.ROWSDETAILBean> rows_detail = userDetailBean.getROWS_DETAIL();
                    saveData(rows_detail);
                }
            }

            @Override
            public void onFailure(String onError) {

            }
        });
    }

    private void getServerName(List<UserDetailBean.ROWSDETAILBean> rows_detail, String username) {
        for (UserDetailBean.ROWSDETAILBean item: rows_detail) {
            if(item.getUsername().equals(username)){
                Intent intent = new Intent();
                intent.putExtra(USER_SERVER_NAME,item.getPname());
                setResult(RESULT_OK,intent);
                finish();
            }
        }
    }

    //存储数据
    private void saveData(List<UserDetailBean.ROWSDETAILBean> userInfoList) {
        mProgrssDialog.setMessage("正在存储，请稍后。。。。。。");
        mProgrssDialog.show();
        List<DBUserInfoBean> all = LitePal.findAll(DBUserInfoBean.class);
        if(all.size()!=0){
            LitePal.deleteAll(DBUserInfoBean.class);
        }
        ArrayList<DBUserInfoBean> dbUserInfoBeans = new ArrayList<>();
        for (UserDetailBean.ROWSDETAILBean item : userInfoList) {
            DBUserInfoBean dbUserInfoBean = new DBUserInfoBean(
                    item.getUsername(),item.getPname(),item.getPcardid()
                    , item.getPsex(),item.getPtel(),item.getPregisterdate()
            ,item.getEmail());
            dbUserInfoBeans.add(dbUserInfoBean);
        }
        LitePal.saveAllAsync(dbUserInfoBeans).listen(new SaveCallback() {
            @Override
            public void onFinish(boolean success) {
                if(success){
                    mProgrssDialog.dismiss();
                    //查询真名
                    getServerName(userInfoList,mEditTextName.getText().toString());
                }
            }
        });
    }

    /**
     * 1.2 检验并设置非空提醒
     *
     * @param pswd
     * @param isLogin
     * @return
     */
    private boolean checkPwd(CharSequence pswd, boolean isLogin) {

        if (TextUtils.isEmpty(pswd)) {
            if (isLogin) {
                mTextInputLayoutPswd.setError(getString(R.string.error_pwd_empty));
                return false;
            }
        } else {
            mTextInputLayoutPswd.setError(null);
        }
        return true;
    }

    /**
     * 1.2 检验并设置非空提醒
     *
     * @param name
     * @param isLogin
     * @return
     */
    private boolean checkName(CharSequence name, boolean isLogin) {
        if (TextUtils.isEmpty(name)) {
            if (isLogin) {
                mTextInputLayoutName.setError(getString(R.string.error_login_empty));
                return false;
            }
        } else {
            mTextInputLayoutName.setError(null);
        }
        return true;
    }


    /**
     * 隐藏键盘输入法
     *
     * @param view The view.
     */
    public static void hideSoftInput(final View view) {
        InputMethodManager imm =
                (InputMethodManager) InitApp.getInstance().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm == null) return;
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0, new ResultReceiver(new Handler()) {
            @Override
            protected void onReceiveResult(int resultCode, Bundle resultData) {
                if (resultCode == InputMethodManager.RESULT_UNCHANGED_SHOWN
                        || resultCode == InputMethodManager.RESULT_SHOWN) {
                    toggleSoftInput();
                }
            }
        });
    }

    /**
     * 软键盘切换
     */
    public static void toggleSoftInput() {
        InputMethodManager imm =
                (InputMethodManager) InitApp.getInstance().getSystemService(Context.INPUT_METHOD_SERVICE);
        //noinspection ConstantConditions
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
        //如果已经显示则隐藏
    }


    public static Boolean IsChecked(Context context){
       return context.getSharedPreferences(USER_INFO,MODE_PRIVATE).getBoolean(USER_ISCHECKED,false);
    }
    public static String getUserName(Context context){
        return context.getSharedPreferences(USER_INFO,MODE_PRIVATE).getString(USER_NAME,"user1");
    }
    public static String getUserPasswd(Context context){
        return context.getSharedPreferences(USER_INFO,MODE_PRIVATE).getString(USER_PASSWD,"123456");
    }

    public static String getPname(Intent data){
        return data.getStringExtra(USER_SERVER_NAME);
    }
}
